package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import cn.itcast.bos.constant.Constants;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	@Qualifier("jmsQueueTemplate")
	@Autowired
	private JmsTemplate jmsTemplate;
	//发送手机验证码信息
	@Action(value = "customer_sendSms")
	public String sendSms() throws IOException {
		// 手机号保存在Customer对象
		// 生成短信验证码
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将短信验证码 保存到session
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(),randomCode);
		System.out.println("生成手机验证码为：" + randomCode);
		// 编辑短信内容
		final String msg = "尊敬的用户您好，本次获取的验证码为：" + randomCode
				+ ",服务电话：4006184000";
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone",model.getTelephone());
				mapMessage.setString("msg",msg);
				return mapMessage;
			}
		});

		/*//使用Utils短信发送工具类完成短信发送
		String s = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);*/
		return NONE;

	}

	// 属性驱动
	private String checkcode;
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	//提交注册时判断手机验证码是否正确
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		//从session获取手机验证码和属性值获取的验证码是否正确
		String tele = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (!tele.equals(checkcode)){
			System.out.println("用户注册失败..");
			return INPUT;
		}

		/*WebClient.create("http://localhost:9002/crm_management/services/customerService/saveCustomer")
				.type(MediaType.APPLICATION_JSON).put(model);*/
		WebClient
				.create("http://localhost:9002/crm_management/services" + "/customerService/saveCustomer")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("客户注册成功...");
		//删除session中的验证码
		ServletActionContext.getRequest().getSession().removeAttribute(model.getTelephone());

		//自动生成32位邮箱激活验证码
		String str = RandomStringUtils.randomNumeric(32);
		//将激活码存入redis缓存服务器中
		redisTemplate.opsForValue().set(model.getTelephone(),str,24,TimeUnit.HOURS);

		//使用工具自动发送邮件
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone() + "&activecode=" + str + "'>速运快递邮箱绑定地址</a>";
		System.out.println(content);
		MailUtils.sendMail("用户注册激活邮件",content,model.getEmail());

		return SUCCESS;
	}


	// 属性驱动
	private String activecode;
	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	//激活mail方法
	@Action("customer_activeMail")
	public String activeMail() throws IOException {
		String str = redisTemplate.opsForValue().get(model.getTelephone());
		//判断从缓存服务器中获取的激活码与URL传入的激活码是否匹配
		if (str == null ||!str.equals(activecode)){
			//激活码不匹配
			ServletActionContext.getResponse().getWriter().println("active file..激活码不正确");
		}else{
			//激活码匹配，此处需要判断该账户是否已经激活
			Integer type = WebClient.create("http://192.168.11.38:9002/crm_management/services/customerService/queryActive/telephone/"
					+ model.getTelephone()).type(MediaType.APPLICATION_JSON).get(Integer.class);
			System.out.println(type);
			if (type==null||type!=1){
				//激活账户
				WebClient.create("http://192.168.11.38:9002/crm_management/services/customerService/updateActive/telephone" +
						"" +
						"/"
						+ model.getTelephone()).accept(MediaType.APPLICATION_JSON).get();
				ServletActionContext.getResponse().getWriter()
						.println("successful,邮箱绑定成功！");
			}else{
				//账户已激活
				ServletActionContext.getResponse().getWriter().println("stop..账户已经激活成功，请勿重复提交..");
			}

			//删除redis的激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}

	//用户登录customer_login.action

	@Action(value = "customer_login",results = {
			@Result(name = "success",location = "index.html#/myhome",type = "redirect"),
			@Result(name = "login",location = "login.html",type = "redirect")})
	public String login(){
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService/loginCustomer?" +
				"telephone=" + model.getTelephone() + "&password=" + model.getPassword())
				.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if (customer==null){
			return LOGIN;
		}else{
			ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
			return SUCCESS;
		}

	}


}
